import React, { useContext, useEffect, useState } from "react";
import CreateIncludeNsTree from "@pkgs/Layout/CreateIncludeNsTree";
import useFormatMessage from "@pkgs/hooks/useFormatMessage";
import { NsTreeContext } from "@pkgs/Layout/Provider";
import request from "@pkgs/request";
import api from "@common/api";
import _ from "lodash";
import { Spin, message } from "antd";
import DiscoveryForm from "./DiscoveryForm";
import { RouteComponentProps } from "react-router-dom";

interface Props extends RouteComponentProps {}

const fetchData = (params: any) => {
  return request(`${api.discovery}?id=${params.id}&type=${params.type}`);
};

const handleSubmit = (params: any, values: any, data: any) => {
  const { action, type } = params;
  let reqBody = {
    type,
    data: values,
  } as any;
  if (action === "add" || action === "clone") reqBody = [reqBody];
  if (action === "modify") reqBody.data.id = data.id;
  return request(api.discovery, {
    method: action === "modify" ? "PUT" : "POST",
    body: JSON.stringify(reqBody),
  });
};

const DiscoveryFormMain: React.FC<Props> = (props) => {
  const intlFmtMsg = useFormatMessage();
  const nstreeContext = useContext(NsTreeContext);
  const treeNodes = _.get(nstreeContext, "data.treeNodes");

  const params = _.get(props, "match.params");
  const [data, setData] = useState({});
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (params.action === "add") {
      setData({
        nid: _.get(nstreeContext, "data.selectedNode.id"),
      });
      setLoading(false);
    } else {
      fetchData(params)
        .then((res) => {
          setData(res);
        })
        .finally(() => {
          setLoading(false);
        });
    }
  }, [params.id, params.type]);

  const ActiveForm = DiscoveryForm[params.type];

  return (
    <Spin spinning={loading}>
      <ActiveForm
        params={params}
        treeData={treeNodes}
        initialValues={data}
        onSubmit={(values: any) => {
          handleSubmit(params, values, data).then(() => {
            message.success(intlFmtMsg({ id: "msg.modify.success" }));
            props.history.push({
              pathname: `/prometheus/discovery/${params.type}`,
              search: window.location.search,
            });
          });
        }}
      />
    </Spin>
  );
};

export default CreateIncludeNsTree(DiscoveryFormMain);
